/*
 * @Author: zhengzhuang
 * @since: 2020-01-09 16:49:40
 * @lastTime     : 2020-01-11 09:55:07
 * @LastAuthor   : zhengzhuang
 * @文件相对于项目的路径: /wangyueche_driver/lib/pages/index_page.dart
 * @message: 项目主题页 IndexPage
 */

import 'dart:async';

import 'package:C20Driver/provider/driver_information.dart';
import 'package:C20Driver/service/request.dart';
import 'package:C20Driver/utils/app_update.dart';
import 'package:C20Driver/widget/webview_widget.dart';
import 'package:C20Driver/widget/webview_widget.dart';
import 'package:amap_location_fluttify/amap_location_fluttify.dart';
import 'package:amap_map_fluttify/amap_map_fluttify.dart';
import 'package:amap_search_fluttify/amap_search_fluttify.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:C20Driver/event/event_bus.dart';
import 'package:C20Driver/pages/index_page/home_page/home_page.dart';
import 'package:C20Driver/provider/position_information.dart';
import 'package:C20Driver/routers/navigator_util.dart';
import 'package:C20Driver/utils/permission_handler.dart';
import 'package:C20Driver/utils/toast.dart';
import 'package:provider/provider.dart';
import 'package:screen/screen.dart';
import 'index_carpool/index_carpool.dart';
import 'package:fluwx/fluwx.dart' as fluwx;

final webViewKey = GlobalKey<WebviewWidgetState>();

class IndexPage extends StatefulWidget {
  @override
  _IndexPageState createState() => _IndexPageState();
}

class _IndexPageState extends State<IndexPage>
    with
        TickerProviderStateMixin,
        AutomaticKeepAliveClientMixin,
        WidgetsBindingObserver {
  TabController _controller;
  DateTime lastPopTime;
  AmapController _amapControllerAll;

  bool _outPageState = false; // 是否处在当前页面

  List _tabTxt = ["首页", "顺风车", "租车服务"];
  WebviewWidget _webviewWidget;

  String orderID;
  String url;
  DriverInformation provider;

  // List _tabTxt = ["首页"];
  @protected
  bool get wantKeepAlive => true;

  // 初始状态
  @override
  void initState() {
    super.initState();
    _initFluwx();
    provider = Provider.of<DriverInformation>(context, listen: false);
    // _webviewWidget =
    //     WebviewWidget(url: "http://c20h5.voico.cn/", key: webViewKey);
    _webviewWidget =
         WebviewWidget(url: "http://c20h5z.voico.cn/", key: webViewKey);
    // 检测App版本更新
    AppUpdate appUpdate = new AppUpdate();
    appUpdate.getAppUpdate(context);

    /// 初始化高德地图IOS
    AmapService.init(
        iosKey: '235a070ab2f84a85e2789a6426c8bb73',
        androidKey: '9e5e2c6ef7d1bcae4dc590b5dd9d9172');
    AmapCore.init('235a070ab2f84a85e2789a6426c8bb73');

    /// 屏幕常亮
    Screen.keepOn(true);

    //获取userId provider里面的user在homePage里面才获取，这里获取不到;
    //  _getDriverInfo(context).then((value) {});

    /// 监听城际出行订单
    eventBus
        .on<MyEvent>()
        .listen((MyEvent data) => _controller.animateTo(int.parse(data.text)));

    _controller = TabController(
        length: _tabTxt.length, vsync: this, initialIndex: provider.tabIndex);
    // orderID=provider.driverJson['userId'];
    Timer.periodic(new Duration(seconds: 10), (timer) async {
      bool getloca = await _setLocationCity();
      if (getloca) {
        timer.cancel();
        timer = null;
      }
    });
  }

  Future<bool> _setLocationCity() async {
    if (await PermissionHandlerX.position(context)) {
      /// 获取我的定位
      await AmapLocation.fetchLocation().then((res) {
        Provider.of<PositionInformation>(context, listen: false)
            .setCityName(res.city);
        Provider.of<PositionInformation>(context, listen: false)
            .setCityLocation(res.city, res.latLng.latitude,
                res.latLng.longitude, res.address, context);
        return true;
      });
      return true;
    } else {
      return false;
    }
  }

  Future _getDriverInfo(BuildContext context) async {
    return await Request.getDriverInfo(context);
  }

  /// 初始化微信支付
  _initFluwx() async {
    /// 初始化微信
    await fluwx
        .registerWxApi(
            appId: "wxe7d75efc296c65a0",
            doOnAndroid: true,
            doOnIOS: true,
            universalLink: "https://links.huashichuxing.com/driver/")
        .then((onValue) {});
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    //设置适配尺寸 (填入设计稿中设备的屏幕尺寸) 此处假如设计稿是按iPhone6的尺寸设计的(iPhone6 750*1334)
    ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);
    // 显示顶部状态栏, 显示例如华为等产片的底部虚拟按键
    SystemChrome.setEnabledSystemUIOverlays(
        [SystemUiOverlay.top, SystemUiOverlay.bottom]);
    // MqttManage.getInstance().setContext(context);

    // Jpush.getJpushInstance().setContext(context);
    return WillPopScope(
      child: DefaultTabController(
        length: _tabTxt.length,
        child: Scaffold(
          resizeToAvoidBottomInset: false,
          appBar: AppBar(
            leading: IconButton(
              icon: Icon(
                Icons.person,
                size: ScreenUtil().setSp(50.0),
                color: Color(0xffFFFFFF),
              ),
              tooltip: '用户',
              // onPressed: () {},
              onPressed: () =>
                  NavigatorUtil.jumpLeft(context, '/personalCenter'),
            ),
            flexibleSpace: Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(colors: [
                  Color(0xff697794),
                  Color(0xff374258),
                ], begin: Alignment.centerLeft, end: Alignment.centerRight),
              ),
            ),
            title: InkWell(
              child: Container(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    Consumer<PositionInformation>(builder: (ctx, state, child) {
                      return Text(state.driverCurrentCity,
                          style: TextStyle(
                              fontSize: ScreenUtil().setSp(34.0),
                              color: Colors.white));
                    }),
                    Icon(Icons.arrow_drop_down,
                        color: Colors.white38,
                        size: ScreenUtil().setWidth(50.0)),
                    SizedBox(width: ScreenUtil().setWidth(90)),
                  ],
                ),
              ),
              onTap: () => NavigatorUtil.jump(context, '/urbanChoice')
                  .then((value) async {
                if (value == null) return;
                String _valueName = value;

                /// 地理编码（地址转坐标）
                final geocodeList = await AmapSearch.searchGeocode(
                  _valueName,
                  city: _valueName,
                );
                await geocodeList[0].latLng.then((value) async {
                  await AmapSearch.searchReGeocode(
                    LatLng(value.latitude, value.longitude),
                    radius: 200.0,
                  ).then((ReGeocode res) async {
                    eventBus.fire(new SetMapLocation(
                        LatLng(value.latitude, value.longitude)));
                    Provider.of<PositionInformation>(context, listen: false)
                        .setCityLocation(_valueName, value.latitude,
                            value.longitude, await res.formatAddress, context);
                  });
                });
              }),
            ),
            // actions: <Widget>[
            //   IconButton(
            //     icon: Icon(Icons.chat, size: ScreenUtil().setSp(50.0)),
            //     tooltip: '消息',
            //     onPressed: () => NavigatorUtil.jump(context, '/messageCenter'),
            //     // onPressed: () => NavigatorUtil.jump(context, '/qrCapturePage'),
            //   ),
            // ],
            elevation: 0.0, // abbbar阴影
          ),
          body: Column(
            children: [
              Container(
                alignment: Alignment.centerLeft,
                width: ScreenUtil().setWidth(750),
                height: ScreenUtil().setWidth(118),
                decoration: BoxDecoration(
                  gradient: const LinearGradient(
                      begin: Alignment.centerLeft, //右上
                      end: Alignment.centerRight,
                      colors: [
                        Color(0xff697794),
                        Color(0xff374258),
                      ]),
                ),
                child: TabBar(
                  onTap: (tab) {
                    // Provider.of<DriverInformation>(context, listen: false)
                    //     .setTabIndex(tab);
                  },
                  controller: _controller,
                  isScrollable: true,
                  unselectedLabelColor: Color(0xffBDC3CD),
                  labelColor: Colors.white,
                  indicatorColor: Color(0xff3FB956),
                  // 选中
                  indicatorSize: TabBarIndicatorSize.label,
                  // indicatorWeight: ScreenUtil().setWidth(8),
                  indicator: UnderlineTabIndicator(
                      borderSide: BorderSide(
                          color: Color(0xff3FB956),
                          width: ScreenUtil().setWidth(8)),
                      insets: EdgeInsets.symmetric(horizontal: 10.0)),
                  tabs: _tabTxt.map((e) {
                    return Tab(
                      icon: Padding(
                        padding: EdgeInsets.only(
                            left: ScreenUtil().setWidth(10),
                            right: ScreenUtil().setWidth(10)),
                        child: Text(
                          '$e',
                          style: TextStyle(
                            fontSize: ScreenUtil().setSp(34.0),
                            fontWeight: FontWeight.w400,
                          ),
                        ),
                      ),
                    );
                  }).toList(),
                ),
              ),
              Expanded(
                child: TabBarView(
                  physics: new NeverScrollableScrollPhysics(),
                  controller: _controller,
                  children: _buildPages(),
                ),
              ),
//              RaisedButton(onPressed: () {
//                MyDialog.confirm('实名认证', "请完成实名认证", context, () {
//                  NavigatorUtil.jump(context, '/realNameAuthentication');
//                });
//              })
            ],
          ),
        ),
      ),
      onWillPop: () async {
        // 点击返回键的操作
        if (lastPopTime == null ||
            DateTime.now().difference(lastPopTime) > Duration(seconds: 2)) {
          lastPopTime = DateTime.now();
          return ToastX.center('再按一次退出C20出行司机端');
        } else {
          lastPopTime = DateTime.now();
          // 退出app
          return await SystemChannels.platform
              .invokeMethod('SystemNavigator.pop');
        }
      },
    );
  }

  List<Widget> _buildPages() {
    List<Widget> pages = List();
    pages = <Widget>[
      HomePage(),
      // IndexIntercity(),
      IndexCarpool(
        amapControllerCallBack: (AmapController amapController) {
          _amapControllerAll = amapController;
        },
      ),
      _webviewWidget
      // IndexPickup()
    ];
    // _controller.addListener(() {
    //   if (provider.tabIndex == 2) {
    //     webViewKey.currentState.reloadWebView("http://c20h5.voico.cn/");
    //   }
    // });

    return pages;
  }

  // @override
  // void didChangeAppLifecycleState(AppLifecycleState state) {
  //   super.didChangeAppLifecycleState(state);
  //   switch (state) {
  //     //进入应用时候不会触发该状态 应用程序处于可见状态，并且可以响应用户的输入事件。它相当于 Android 中Activity的onResume
  //     case AppLifecycleState.resumed:
  //       print("应用进入前台======");
  //       setState(() {});
  //       break;
  //     //应用状态处于闲置状态，并且没有用户的输入事件，
  //     // 注意：这个状态切换到 前后台 会触发，所以流程应该是先冻结窗口，然后停止UI
  //     case AppLifecycleState.inactive:
  //       print("应用处于闲置状态，这种状态的应用应该假设他们可能在任何时候暂停 切换到后台会触发======");
  //       break;
  //     //当前页面即将退出
  //     case AppLifecycleState.detached:
  //       print("当前页面即将退出======");
  //       break;
  //     // 应用程序处于不可见状态
  //     case AppLifecycleState.paused:
  //       print("应用处于不可见状态 后台======");
  //       break;
  //   }
  // }

  // 销毁状态
  @override
  void dispose() {
    if (_amapControllerAll != null) {
      _amapControllerAll.dispose();
      // _amapControllerAll = null;
    }
    super.dispose();
  }
}
